package mirrormonkey.util.netevent.server.tools;

import java.util.LinkedList;
import java.util.List;

import junit.framework.Assert;

import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection;
import com.jme3.network.Server;

/**
 * Tracks <tt>HostedConnection</tt>s that have been added and removed and
 * provides methods to check whether they were the right ones.
 * 
 * @author Philipp Christian Loewner
 * 
 */
public class MockConnectionListener implements ConnectionListener {

	public final List<HostedConnectionEvent> added = new LinkedList<HostedConnectionEvent>();

	public final List<HostedConnectionEvent> removed = new LinkedList<HostedConnectionEvent>();

	@Override
	public void connectionAdded(Server server, HostedConnection conn) {
		added.add(new HostedConnectionEvent(server, conn));
	}

	@Override
	public void connectionRemoved(Server server, HostedConnection conn) {
		removed.add(new HostedConnectionEvent(server, conn));
	}

	public static void reset(MockConnectionListener[] listeners) {
		for (MockConnectionListener l : listeners) {
			l.added.clear();
			l.removed.clear();
		}
	}

	public void checkAdded(HostedConnectionEvent[] events) {
		checkSame(added, events);
	}

	public static void checkAdded(MockConnectionListener[] listeners,
			HostedConnectionEvent[] events) {
		for (MockConnectionListener l : listeners) {
			l.checkAdded(events);
		}
	}

	public void checkRemoved(HostedConnectionEvent[] events) {
		checkSame(removed, events);
	}

	public static void checkRemoved(MockConnectionListener[] listeners,
			HostedConnectionEvent[] events) {
		for (MockConnectionListener l : listeners) {
			l.checkRemoved(events);
		}
	}

	private void checkSame(List<HostedConnectionEvent> list,
			HostedConnectionEvent[] array) {
		Assert.assertEquals(array.length, list.size());
		int i = 0;
		for (HostedConnectionEvent e : list) {
			Assert.assertSame(e.server, array[i].server);
			Assert.assertSame(e.connection, array[i++].connection);
		}
	}

	public static class HostedConnectionEvent {

		public final Server server;
		public final HostedConnection connection;

		public HostedConnectionEvent(Server server, HostedConnection connection) {
			this.server = server;
			this.connection = connection;
		}

	}

}